<template lang="pug">
.upload-attr
  .upload-section(v-if="form.sampleMaterialAttributeList.length")
    .upload-section-header
      .upload-section-title 材料属性（必填）
    .upload-section-content
      .upload-form-bd
        .upload-form-bd-header
          .form-item-info 提醒：该属性与材料白皮书相关，且与物料间样品参数相关，请按规定填写数据
        .form-item.form-item-start.form-description-item(v-for="item, index in form.sampleMaterialAttributeList" :key="index")
          .form-item-label.form-item-label_import {{item.attributeName}}
          .form-item-fixed-attr
            el-input(
              v-model="item.attributeValue"
              type="textarea"
              placeholder="请输入说明（必填）"
              resize="none"
              rows="6"
            )
  .upload-section
    .upload-section-header
      .upload-section-title 自定义材料属性
    .upload-section-content
      .upload-form-bd
        .upload-form-bd-header
          .form-bd-title 属性设置
          el-popover(
            placement="bottom"
            popper-class="model-popover"
            width="200"
            trigger="click"
            :visible-arrow="false"
          )
            .model-body
              .model-list
                .model-item(v-for="item, index in attrModal" :key="index" @click.stop="changeModel")
                  .model-item-title {{item.name}}
                  .model-item-handle
                    .iconfont.icon-edit(@click.stop="editModelList(item, 'editAttrModel')")
                    .iconfont.icon-trash(@click.stop="delAttrModelList(item)")
            .form-bd-select(slot="reference" v-show="attrModal.length")
              .form-bd-select-value {{currentAttrModel.name}}
              .form-bd-select-icon.el-icon-arrow-down
          .form-bd-header-handle
            .form-bd-header-btn(v-if="currentAttrModel.id" @click="saveAttrModal") 保存模板
            .form-bd-header-btn(@click="addSpecModal('editAttrModel')") 存为新模板
        .form-item.form-item-start
          .form-item-label.form-item-label_import 材料属性
          .form-item-spec
            draggable(:list="form.attr", v-bind="dragOptions")
              transition-group(type="transition" name="flip-list" tag="div")
                .spec-table(v-for="(item, index) in form.attr", :key="`attr_${index}`" v-if="form.attr.length")
                  .spec-table-header
                    .spec-hd-value
                      .spec-hd-value-label 属性名称
                      .spec-hd-value-bd
                        el-input(size="mini" placeholder="请输入属性" v-model="item.name" @change="changeAttrName(item, index)")
                    .spec-hd-handle(@click="delAttr(item, index)")
                      .icon-trash
                      .spec-hd-handle-btn 删除
                  .spec-table-body
                    .spec-table-body-label 属性值
                    .spec-table-body-value(v-for="(row, rowIndex) in item.values" :key="rowIndex" v-if="item.name")
                      .spec-table-body-input
                        .iconfont.el-icon-error(@click="delAttrValue(row, rowIndex, item.values)")
                        el-input(v-model="row.name" size="mini")
                    .spec-table-body-ft(@click="addAttr(item)" v-if="item.name") 添加属性值
            .spec-table-handle
              el-button(size="mini" icon="el-icon-plus" plain  @click="settingAttr") 添加属性
  .content-footer
    el-button(name="primary" @click="prev") 上一步，选择材料信息
    el-button(type="primary" @click="next") 下一步，填写材料关联
  model-name-dialog(
    :show="showModelDialog"
    :skuList="form.attr"
    :item="currentModelItem"
    :modelDialogType="modelDialogType"
    @close="closeModelDialog"
    @confirm="confirmModelDialog"
  )
</template>

<script>
import draggable from 'vuedraggable'
import modelNameDialog from '@/components/modal/modelNameDialog'
import { getMaterialTemplate, getCateAttributeList } from 'api'
import { mapState, mapActions } from 'vuex'
export default {
  name: 'attrModule',
  components: {
    draggable,
    modelNameDialog
  },
  data () {
    return {
      showModelDialog: false,
      currentModelItem: {},
      modelDialogType: '',
      attrModal: [],
      currentAttrModel: {},
      form: {
        sampleMaterialAttributeList: [],
        attr: [],
        diydata: {
          attr: []
        }
      }
    }
  },
  computed: {
    dragOptions () {
      return {
        animation: 60,
        handle: '.spec-table'
      }
    },
    ...mapState({
      materialData: state => state.material.materialData
    })
  },
  methods: {
    ...mapActions([
      'changeMaterialData'
    ]),
    prev () {
      this.$emit('prev')
    },
    next () {
      try {
        if (!this.form.attr.length) {
          this.$message.error('材料属性至少有一项！')
          return
        }
        let attrFilter = this.form.attr.every(item => {
          let isChildName = item.values.every(row => !!row.name)
          return item.name && item.values.length && isChildName
        })
        if (!attrFilter) {
          this.$message.error('请仔细检查材料属性是否有未填写的字段！')
          return
        }
        if (this.form.sampleMaterialAttributeList.length) {
          let isValid = this.form.sampleMaterialAttributeList.every(item => !!item.attributeValue)
          if (!isValid) {
            this.$message.error('请仔细检查固定属性是否有未填写的字段！')
            return
          }
        }
        this.changeMaterialData({ ...this.materialData, form: { ...this.form, diydata: { attr: this.form.attr } } })
        this.$emit('next')
      } catch (err) {
        console.log(err)
      }
    },
    // 关闭模板名称弹窗
    closeModelDialog () {
      this.showModelDialog = false
      this.currentModelItem = {}
    },
    // 确认模板名称
    confirmModelDialog () {
      this.$message.success('保存成功！')
      this.currentModelItem = {}
      this.getCateModelList()
      this.showModelDialog = false
    },
    // 替换模板
    changeModel () {
      this.$confirm('您确定要使用该模型吗？使用后会覆盖当前页面数据', '使用模型', {
        customClass: 'sold-message_box',
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'sold-button_sure'
      }).then(async () => {
        this.form.attr = item.value
        this.currentAttrModel = item
      })
    },
    // 编辑模板名称
    editModelList (item, type) {
      this.modelDialogType = type
      this.currentModelItem = item
      this.showModelDialog = true
    },
    // 删除模板
    delAttrModelList (item) {
      this.$confirm('确定删除该模型？删除模型不影响您现在编辑的内容', '删除模型提示', {
        customClass: 'sold-message_box',
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'sold-button_sure'
      }).then(async () => {
        try {
          await this.$axios.post(deleteTemplate, { content: { id: item.id } })
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          await this.getCateModelList()
        } catch (err) {
          this.$message.error(err.msg)
        }
      })
    },
    // 新增规格模板
    async addSpecModal (type) {
      this.modelDialogType = type
      this.showModelDialog = true
    },
    // 属性设置
    // 保存属性模板
    async saveAttrModal () {
      try {
        let query = { ...this.currentAttrModel }
        query.value = JSON.stringify(query.value)
        await this.$axios.post(saveMaterialTemplate, { content: { ...query } })
        this.$message.success('保存成功！')
      } catch (err) {
        this.$message.error(err.msg)
      }
    },
    // 添加属性项
    async settingAttr () {
      try {
        this.form.attr.push({
          name: '',
          values: []
        })
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        // this.goodsModel.attrValue = ''
      } catch ({ msg }) {
        this.$message.error(msg)
      }
    },
    // 修改属性名称
    changeAttrName (item, index) {
      if (!item.name) {
        this.form.attr[index].values = []
      }
    },
    // 删除属性项
    async delAttr (item, index) {
      this.$confirm('确定删除该属性吗？', '删除属性提示', {
        customClass: 'sold-message_box',
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'sold-button_sure'
      }).then(async () => {
        this.form.attr.splice(index, 1)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      })
    },
    // 添加属性值
    async addAttr (item) {
      try {
        item.values.push({
          is_selected: true,
          name: ''
        })
      } catch (err) {
        this.$message.error(err.msg)
      }
    },
    // 删除属性值
    delAttrValue (row, index, arr) {
      arr.splice(index, 1)
    },
    // 获取属性模板
    async getAttrModel () {
      try {
        const { ResultSet } = await this.$axios.post(getMaterialTemplate, { type: 3 })
        if (ResultSet.userData.sampleTemplateList.length) {
          ResultSet.userData.sampleTemplateList.forEach(item => {
            if (item.value.length) {
              item.value.forEach(row => {
                if (row.values.length) {
                  row.values.forEach(col => {
                    col.is_selected = true
                  })
                }
              })
            }
          })
          if (!this.$route.params.id) {
            this.currentAttrModel = ResultSet.userData.sampleTemplateList[0]
            // ResultSet.userData.templateList.forEach(item => {
            //   this.currentAttrModel = 
            //   if (item.is_default) {
            //     this.currentAttrModel = item
            //   }
            // })
          }
          this.attrModal = ResultSet.userData.sampleTemplateList
          // console.log(ResultSet.userData.templateList)
        }
      } catch (err) {
        this.$message.error(err.msg)
      }
    },
    async getAttrDetail () {
      try {
        if (!this.form.diydata || !this.form.diydata.attr || !this.form.diydata.attr.length) {
          this.form.attr = this.currentAttrModel.value
        }
      } catch (err) {
        console.log(err)
        this.$message.error(err.msg)
      }
    },
    async getCategoryFixAttribute (id) {
      try {
        const { ResultSet } = await this.$axios.post(getCateAttributeList, { classificationId: parseInt(id) })
        // const { ResultSet } = await this.$axios.post(getCateAttributeList, { classificationId: 1163 })
        if (ResultSet.Result && ResultSet.Result.length) {
          this.form.sampleMaterialAttributeList = ResultSet.Result.filter(item => item.isRequired)
        } else {
          this.form.sampleMaterialAttributeList = []
        }
      } catch (err) {
        console.log(err)
          this.$message.error(err.ResultSet.errors)
      }
    },
  },
  async created () {
    await this.getAttrModel()
    this.form = { ...this.form, ...this.materialData.form, attr: this.materialData.form.diydata.attr || [] }
    if (!this.$route.params.id) await this.getAttrDetail()
    // this.getCategoryFixAttribute(1163)
    if (!this.form.sampleMaterialAttributeList || !this.form.sampleMaterialAttributeList.length) {
      if (!this.$route.params.id && this.materialData.category && this.materialData.category.second_id) this.getCategoryFixAttribute(this.materialData.category.second_id)
    }
  },
}
</script>

<style lang="scss" scoped>
.upload-attr {
  background: #fff;
}
.upload-section {
  width: 100%;
  margin-top: 20px;
  background: #fff;
  padding: 25px 0;
  border-radius: 4px;
  display: flex;
}
.upload-section-header {
  width: 250px;
  padding: 0 22px;
  .upload-section-title {
    padding: 10px 16.5px;
    border-radius: 0 50px 50px 0;
    background: #FF708B;
    font-size: 18px;
    line-height: 26px;
    color: #fff;
  }
}
.upload-section-content {
  flex: 1;
  padding: 0 22px;
}
.upload-form-bd {
  margin-bottom: 20px;
  background: #fff;
  transition: all .5s;
}
.upload-form-bd-header {
  width: 100%;
  padding: 10px 20px;
  margin-bottom: 20px;
  background: #FAFAFA;
  display: flex;
  align-items: center;
}
.form-bd-title {
  font-size: 14px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #333333;
  line-height: 20px;
}
.form-item {
  display: flex;
  align-items: center;
  margin-top: 15px;
  font-size: 12px;
  color: #333333;
  &.form-item-start {
    align-items: flex-start;
    .form-item-label {
      line-height: 60px;
      margin-right: 20px;
    }
  }
  &.spec-sku {
    .form-item-label {
      line-height: 20px;
      margin-right: 20px;
    }
  }
  &.form-item-top {
    align-items: flex-start;
  }
  & .form-item-body {
    display: flex;
    align-items: center;
    width: 1000px;
  }
  & .form-item-label {
    min-width: 110px;
    text-align: right;
    margin-right: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
    &.form-item-label_import {
      &:after {
        content: '*';
        color: #FF0000;
      }
    }
    &.form-item-label_strong {
      font-weight: 600;
      font-size: 14px;
    }
  }
  & .form-item-bd {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-left: 5px;
    min-width: 340px;
    & .el-checkbox-group {
      margin-right: 40px;
      & .el-checkbox {
        margin-right: 20px;
      }
    }
    & .form-item-bd_input {
      display: flex;
      min-width: 130px;
      margin-bottom: 6px;
      height: 40px;
      line-height: 40px;
      padding-left: 21px;
      align-items: center;
      & .el-input {
        width: 200px;
        margin-right: 10px;
      }
      & .form-item-bd_input-value {
        color: #0f73e6;
        cursor: pointer;
        text-decoration: underline;
      }
    }
  }
  & .form-item-bd_setting {
    display: flex;
    align-items: center;
    margin-left: 5px;
    margin-right: 10px;
    width: 150px;
    max-width: 150px;
  }
}
.form-item-fixed-attr {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}
.fixed-attr-item {
  width: 50%;
  margin-bottom: 20px;
  .fixed-attr-item-bd {
    padding: 0 15px;
  }
  .fixed-attr-item-header {
    width: 100%;
    height: 60px;
    padding: 0 30px;
    display: flex;
    align-items: center;
    background: #FAFAFA;
    border: 1px solid #D9D9D9;
    .fixed-attr-item-header_label {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
    }
    .fixed-attr-item-header_value {
      margin-left: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
    }
  }
  .fixed-attr-item-value {
    padding: 24px 46px;
    background: #FFFFFF;
    border: 1px solid #D9D9D9;
    border-top: none;
    display: flex;
    align-items: center;
    .fixed-attr-item-value_label {
      margin-right: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #333333;
      line-height: 20px;
      flex-shrink: 0;
      margin-bottom: 10px;
    }
    .fixed-attr-item-value_bd {
      display: flex;
      align-items: center;
      margin-right: 20px;
      margin-bottom: 10px;
    }
  }
}
.form-item-info {
  margin-left: 10px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #CCCCCC;
  line-height: 20px;
}
.model-body {
  max-height: 200px;
  overflow-y: auto;
  .model-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 10px;
  }
  .model-item-title {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
  }
  .model-item-handle {
    display: flex;
    align-items: center;
    .iconfont {
      margin-left: 10px;
    }
  }
  .model-item-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 20px;
  }
  .model-item {
    padding: 9px 20px;
    border-bottom: 1px solid #DDDDDD;
    cursor: pointer;
    &:hover {
      background: #F8F8F8;
      .model-item-setting {
        display: inline-block;
      }
      .model-item-time_handle {
        display: inline-block;
      }
    }
  }
  .model-item-default {
    font-size: 14px;
    color: #333333;
  }
  .model-item-setting {
    display: none;
    font-size: 14px;
    color: #0f73e6;
    cursor: pointer;
  }
  .model-item-time {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    line-height: 20px;
    .model-item-time_bd {
      font-size: 14px;
      color: #999999;
    }
    .model-item-time_handle {
      display: none;
      font-size: 14px;
      color: #C2212A;
    }
  }
}
.form-bd-select {
  width: 150px;
  height: 28px;
  padding: 4px 10px;
  margin-left: 20px;
  background: #FFFFFF;
  border-radius: 2px;
  border: 1px solid #D9D9D9;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #333333;
  cursor: pointer;
  .form-bd-select-value {
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    line-height: 20px;
    &.form-bd-select-value-placeholder {
      color: #ccc;
    }
  }
}
.form-bd-header-handle {
  display: flex;
  align-items: center;
  .form-bd-header-btn {
    padding: 5px 18px;
    margin-left: 20px;
    background: #ECECEC;
    border-radius: 2px;
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 18px;
    cursor: pointer;
  }
}
.form-item-spec {
  flex: 1;
}
.spec-table-handle {
  margin-top: 20px;
  display: flex;
  align-items: center;
  .spec-table-handle-info {
    margin-left: 10px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #CCCCCC;
    line-height: 20px;
  }
}
.spec-table-body {
  padding: 24px 46px;
  background: #FFFFFF;
  border: 1px solid #D9D9D9;
  border-top: none;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .spec-table-body-label {
    margin-right: 20px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
    flex-shrink: 0;
    margin-bottom: 10px;
  }
  .spec-table-body-value {
    display: flex;
    align-items: center;
    margin-right: 20px;
    margin-bottom: 10px;
    .spec-table-body-input {
      position: relative;
      width: 108px;
      & .iconfont {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        font-size: 16px;
        transform: translate(50%, -50%);
        z-index: 99;
        cursor: pointer;
      }
      &:hover {
        & .iconfont {
          display: inline-block;
        }
      }
    }
    .spec-table-body-img {
      position: relative;
      width: 28px;
      height: 28px;
      margin-left: 10px;
      background: #FFFFFF;
      border: 1px solid #DDDDDD;
      background-position: center;
      background-repeat: no-repeat;
      background-size: contain;
      .iconfont {
        position: absolute;
        top: 0;
        right: 0;
        font-size: 16px;
        transform: translate(50%, -50%);
      }
    }
    .spec-table-body-upload {
      position: relative;
      margin-left: 10px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 20px;
      cursor: pointer;
      & .el-input {
        width: 68px;
        height: 28px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        opacity: 0;
      }
    }
  }
  .spec-table-body-ft {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #0F73E6;
    line-height: 20px;
    cursor: pointer;
    margin-bottom: 10px;
  }
}
.spec-table {
  margin-bottom: 20px;
}
.spec-table-header {
  width: 100%;
  height: 60px;
  padding: 0 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #FAFAFA;
  border: 1px solid #D9D9D9;
}
.spec-hd-value {
  display: flex;
  align-items: center;
  .spec-hd-value-label {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
  }
  .spec-hd-value-bd {
    width: 108px;
    margin-left: 20px;
  }
}
.spec-hd-handle {
  display: flex;
  align-items: center;
  cursor: pointer;
  .iconfont {
    font-size: 14px;
    background: #999999;
  }
  .spec-hd-handle-btn {
    margin-left: 10px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #666666;
    line-height: 20px;
    cursor: pointer;
  }
}
.content-footer {
  margin-top: 20px;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #ebeef5;
}
</style>